package com.lagou.filter;

import com.lagou.service.TokenMapper;
import io.netty.handler.codec.http.cookie.Cookie;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.netty.http.Cookies;

import java.util.List;
import java.util.Map;

public class MyFilter implements GlobalFilter, Ordered {

    @Autowired
    private TokenMapper tokenMapper;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String uri = request.getURI().toString();

        //登录和注册不进行拦截
        if (uri.contains("login") || uri.contains("register")) {
            return chain.filter(exchange);
        }

        MultiValueMap<String, HttpCookie> multiValueMap = request.getCookies();
        List<HttpCookie> cookies = multiValueMap.get("token");
        String token = cookies.get(0).getValue();
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }
        //数据库查询token是否存在
        int count = tokenMapper.hasToken(token);
        if (count > 0) {
            return chain.filter(exchange);
        } else {
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
